package com.tonels.AsyncHandlerInterceptor.task;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
@Slf4j
public class TaskExecutor {

    @Async("asyncExecutor")
    public CompletableFuture<String> task1(String filePath) throws InterruptedException {
        long startTime = System.currentTimeMillis();
        String name = Thread.currentThread().getName();
        Thread.sleep(1000L);    // 延迟 1 秒
        String result = "线程 ： " + name + ": " + filePath;
        log.info("线程结果{}，耗时 {} ms", result, System.currentTimeMillis() - startTime);
        return CompletableFuture.completedFuture(result);
    }

    @Async("anotherThread")
    public void task2(String taskName,List<String> filePaths) throws InterruptedException {

        log.info("当前线程：{}",Thread.currentThread().getName());

        long startTime = System.currentTimeMillis();

        List<CompletableFuture<String>> result = Lists.newCopyOnWriteArrayList();

        filePaths.stream().map(String::valueOf).parallel().forEach(e -> {
            try {
//                TaskExecutor taskExecutor = new TaskExecutor();
//                CompletableFuture<String> stringCompletableFuture = taskExecutor.task1(e);
                CompletableFuture<String> stringCompletableFuture = this.task1(e);
                result.add(stringCompletableFuture);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        });

        CompletableFuture[] cfs = result.toArray(new CompletableFuture[0]);
        //等待总任务完成，但是封装后无返回值，必须自己whenComplete()获取
        CompletableFuture.allOf(cfs).join();
        log.info("Thread：{},video TaskName: {} 处理完成 ,list size = {},总耗时 {} ms",
                Thread.currentThread().getName(),
                taskName,
                result.size(),
                System.currentTimeMillis() - startTime);

        // todo
        // http 数据传输
        System.out.println("任务合并后，继续 http 发送");
    }


}
